package org.ch02.sk.demo11;

import java.beans.*;
import java.lang.reflect.Method;

/**
 * @author XCH
 * @date 2025 - 03 - 25
 */
public class BeanUtil {
    //1、设置何意对象的属性值
    public static void setProperty(Object bean, String propertyName, Object value) throws Exception {
//        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
//        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
//        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
//            if (propertyDescriptor.getName().equals(propertyName)) {
//                propertyDescriptor.getWriteMethod().invoke(bean, value);
//                return;
//            }
//        }
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor(propertyName, bean.getClass());
        Method method = propertyDescriptor.getWriteMethod();
        method.invoke(bean, value);

    }

   // 2、获取任意对象的属性值
    public static Object getProperty(Object bean, String propertyName) throws Exception {
//        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
//        MethodDescriptor [] methodDescriptors = beanInfo.getMethodDescriptors();
//        for (MethodDescriptor methodDescriptor : methodDescriptors) {
//            if (methodDescriptor.getName().equals("get" + propertyName)) {
//                return methodDescriptor.getMethod().invoke(bean);
//            }
//        }
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor(propertyName, bean.getClass());
        Method method = propertyDescriptor.getReadMethod();
        return method.invoke(bean);
    }

    //3、复制某个对象的属性值到另一个对象中
    public static void copyProperties(Object source, Object target) throws Exception {
        BeanInfo beanInfo = Introspector.getBeanInfo(source.getClass(), Object.class);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            try {
                Object value = propertyDescriptor.getReadMethod().invoke(source);
                propertyDescriptor.getWriteMethod().invoke(target, value);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
//        Person person = new Person();
//        setProperty(person, "name", "李四");
//        setProperty(person, "age", 20);
//        System.out.println(person.getName());
//        System.out.println(person.getAge());

//        Person person = new Person("aaa", 20);
//        System.out.println(getProperty(person, "name"));
//        System.out.println(getProperty(person, "age"));

        Person person1 = new Person("aaa", 20);
        Person person2 = new Person();
        copyProperties(person1, person2);
        System.out.println(person2.getName());
        System.out.println(person2.getAge());
    }
}
